import { AlarmLimit, ModalConfirm, ScreenAreaPatientMsg } from '@/components';
import EcgCharts from '@/components/EcgCharts';
import { ALARM_THRESHOLD_MAP } from '@/constants';
import { patientDischarged } from '@/services/patientMsg';
import { EllipsisOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { useDebounce } from 'ahooks';
import { Dropdown, message, Popconfirm } from 'antd';
import { stringify } from 'querystring';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import closeNotice from '../../../public/images/closeNotice.png';
import manPng from '../../../public/images/man.png';
import partMsg from '../../../public/images/partMsg.png';
import womanPng from '../../../public/images/woman.png';
import './index.less';

interface EcgModuleProps {
  itemData: any;
  onCloseWs?: any;
  refreshList?: any;
}
const EcgModule = React.memo(
  ({ itemData, onCloseWs, refreshList }: EcgModuleProps) => {
    // 优化：用 useMemo 缓存，仅当 itemData?.alarms 或映射规则变化时更新
    const targetAlarms = useMemo(() => {
      if (!itemData?.alarms) return [];
      return itemData.alarms.map((alarmsItems: any) => {
        for (const key in ALARM_THRESHOLD_MAP) {
          if (alarmsItems.msg.includes(key)) {
            return {
              level: alarmsItems.level,
              msg: alarmsItems.msg.replace(
                key,
                ALARM_THRESHOLD_MAP[key as keyof typeof ALARM_THRESHOLD_MAP],
              ),
            };
          }
        }
      });
    }, [itemData?.alarms]); // 仅依赖原始数据和映射规则
    const debouncedAlarmsLength = useDebounce(targetAlarms.length, {
      wait: 300,
    });

    const ScreenAreaPatientMsgRef = useRef<any>(null);
    const AlarmLimitRef = useRef<any>(null);
    const modalConfirmRef = useRef<any>(null);
    const patientLimits = itemData?.patient?.patientLimits || [];
    const [modItem, setmodItem] = useState<any>(null);
    const [currentIndex, setCurrentIndex] = useState(0);
    const intervalRef: any = useRef(null);

    //心率  heartRate
    const heartRateObj =
      patientLimits.find((its: any) => {
        return its.itemCode === 'heartRate';
      }) || {};
    //血氧  spo2Value
    const spo2ValueObj =
      patientLimits.find((its: any) => {
        return its.itemCode === 'spo2Value';
      }) || {};
    //温度1  temperature1
    const temperature1Obj =
      patientLimits.find((its: any) => {
        return its.itemCode === 'temperature1';
      }) || {};
    //温度2  temperature2
    const temperature2Obj =
      patientLimits.find((its: any) => {
        return its.itemCode === 'temperature2';
      }) || {};

    const goPersonalHomePage = () => {
      if (itemData.id) {
        onCloseWs && onCloseWs();
        history.push({
          pathname: '/personalHomePage',
          search: stringify({
            patientId: itemData?.patient?.id || '',
            screenAreaId: itemData?.id || '',
          }),
        });
      }
    };
    const handleOption = async (type: string) => {
      setmodItem({
        modKey: type,
      });
      if (type === 'ScreenAreaPatientMsg') {
        ScreenAreaPatientMsgRef?.current?.handleModalShow(itemData);
      } else if (type === 'PatientLeave') {
        modalConfirmRef?.current?.handleModalShow('该患者确定出院?');
      } else if (type === 'PatientDetail') {
        goPersonalHomePage();
      } else if (type === 'AlarmLimit') {
        if (itemData?.patient?.id) {
          AlarmLimitRef?.current?.handleModalShow(itemData);
        }
      }
    };
    const modalSuccessCallback = async () => {
      if (modItem.modKey === 'PatientLeave') {
        const res = await patientDischarged({
          patientId: itemData?.patient?.id,
        });
        if (res?.code === 200) {
          message.success('解绑成功');
          modalConfirmRef?.current?.handleModalShow();
          refreshList();
          return true;
        }
      }
    };
 
    
    // 轮询逻辑依赖防抖后的长度
    useEffect(() => {
      // 清除旧定时器
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }

      if (debouncedAlarmsLength > 1) {
        intervalRef.current = setInterval(() => {
          setCurrentIndex((prev) => (prev + 1) % debouncedAlarmsLength);
        }, 1000);
      }

      return () => {
        if (intervalRef.current) {
          clearInterval(intervalRef.current);
          intervalRef.current = null;
        }
      };
    }, [debouncedAlarmsLength]); // 依赖防抖后的值
    
    return (
      <div className="ecg-module-wrapper">
        <div className="user-info-wrapper">
          {/* 操作 */}
          <div className="option-wrapper">
            <Dropdown
              trigger={['click']}
              menu={{
                items: [
                  {
                    label: '分区关联',
                    key: 'ScreenAreaPatientMsg',
                    onClick: ({ domEvent }) => {
                      domEvent.stopPropagation();
                      handleOption('ScreenAreaPatientMsg');
                    },
                  },
                  {
                    label: '患者离院',
                    key: 'PatientLeave',
                    disabled: !itemData?.patient?.id,
                    onClick: ({ domEvent }) => {
                      domEvent.stopPropagation();
                      handleOption('PatientLeave');
                    },
                  },
                  {
                    label: '详情视图',
                    key: 'PatientDetail',
                    disabled: !itemData?.patient?.id,
                    onClick: ({ domEvent }) => {
                      domEvent.stopPropagation();
                      handleOption('PatientDetail');
                    },
                  },
                ],
              }}
              placement="bottomRight"
              arrow
            >
              <div
                className="icon2"
                onClick={(event) => {
                  event.stopPropagation(); // 阻止事件冒泡
                }}
              >
                <img src={partMsg} alt="" />
              </div>
            </Dropdown>
          </div>
          <div className='patient-info'>
            {/* manPng */}
            {itemData?.patient?.sex && (
              <>
                {itemData?.patient?.sex == 1 ? (
                  <img src={manPng} alt="" />
                ) : (
                  <img src={womanPng} alt="" />
                )}
              </>
            )}
            {itemData?.patient?.name || '---'}
            {itemData?.patient?.ward?.name && (
              <> {itemData?.patient?.ward?.name}</>
            )}
            {itemData?.patient?.ward?.bed?.code && (
              <> {itemData?.patient?.ward?.bed?.code}</>
            )}
          </div>
        </div>
        <div
          className="ecg-main-wrapper"
          onClick={() => handleOption('AlarmLimit')}
        >
          {itemData?.id && (
            <>
              {itemData?.status === 'offline' ? (
                <div className="device-offline">设备离线</div>
              ) : (
                <>
                  {/* 监护仪 */}
                  {itemData?.device &&
                    itemData?.device.type == 1 &&
                    itemData?.device?.ecgYAxisData &&
                    itemData?.device?.ecgYAxisData?.length > 0 && (
                      <div className="monitor-item">
                        <div className="ecg-charts-wrapper">
                          <div className="ecg-charts-inner">
                            {itemData?.device?.ecgYAxisData.map(
                              (items: any) => {
                                return (
                                  <div
                                    className={`ecg-charts-item  item_${itemData.device.ecgYAxisData?.length}`}
                                    key={items.key}
                                  >
                                    <EcgCharts
                                      itemData={{
                                        ...items,
                                        gain: itemData?.gain || 1,
                                        ecgFlag: itemData?.ecgFlag || false,
                                      }}
                                    />
                                  </div>
                                );
                              },
                            )}
                          </div>
                        </div>
                        <div className="ecg-desc-wrapper">
                          {/* 心率 */}
                          <div className="ecg-describe-item">
                            <div className="public-wrapper1">
                              <div className="title-show-wrapper">
                                <div className="title1">ECG</div>
                                <div className="title2">bpm</div>
                              </div>
                              {heartRateObj.alarmSwitch === '0' ? (
                                <img
                                  src={closeNotice}
                                  alt=""
                                  className="closeNoticeImg"
                                />
                              ) : (
                                <div className="title4">
                                  <div>{heartRateObj?.upperLimit || '-'}</div>
                                  <div>{heartRateObj?.lowerLimit || '-'}</div>
                                </div>
                              )}
                            </div>
                            <div
                              className={
                                heartRateObj.alarmSwitch === '1' &&
                                (itemData.heartRate > heartRateObj.upperLimit ||
                                  itemData.heartRate < heartRateObj.lowerLimit)
                                  ? heartRateObj.level == 3
                                    ? 'title3 notice'
                                    : heartRateObj.level == 2
                                    ? 'title3 notice1'
                                    : 'title3'
                                  : 'title3'
                              }
                            >
                              {itemData.heartRate}
                            </div>
                          </div>
                          {/* 血氧 */}
                          <div className="ecg-describe-item">
                            <div className="public-wrapper1">
                              <div className="title-show-wrapper">
                                <div className="title1">SpO2</div>
                                <div className="title2">%</div>
                              </div>
                              {spo2ValueObj.alarmSwitch === '0' ? (
                                <img
                                  src={closeNotice}
                                  alt=""
                                  className="closeNoticeImg"
                                />
                              ) : (
                                <div className="title4">
                                  <div>{spo2ValueObj?.upperLimit || '-'}</div>
                                  <div>{spo2ValueObj?.lowerLimit || '-'}</div>
                                </div>
                              )}
                            </div>
                            <div
                              className={
                                spo2ValueObj.alarmSwitch === '1' &&
                                (itemData.spo2Value > spo2ValueObj.upperLimit ||
                                  itemData.spo2Value < spo2ValueObj.lowerLimit)
                                  ? spo2ValueObj.level == 3
                                    ? 'title3 notice'
                                    : spo2ValueObj.level == 2
                                    ? 'title3 notice1'
                                    : 'title3'
                                  : 'title3'
                              }
                            >
                              {itemData.spo2Value}
                            </div>
                          </div>
                          {/* 温度1 */}
                          <div className="ecg-describe-item">
                            <div className="public-wrapper1">
                              <div className="title-show-wrapper">
                                <div className="title1">温度1</div>
                                <div className="title2">T</div>
                              </div>
                              {temperature1Obj.alarmSwitch === '0' ? (
                                <img
                                  src={closeNotice}
                                  alt=""
                                  className="closeNoticeImg"
                                />
                              ) : (
                                <div className="title4">
                                  <div>
                                    {temperature1Obj?.upperLimit || '-'}
                                  </div>
                                  <div>
                                    {temperature1Obj?.lowerLimit || '-'}
                                  </div>
                                </div>
                              )}
                            </div>
                            <div
                              className={
                                temperature1Obj.alarmSwitch === '1' &&
                                (itemData.temperature1 >
                                  temperature1Obj.upperLimit ||
                                  itemData.temperature1 <
                                    temperature1Obj.lowerLimit)
                                  ? temperature1Obj.level == 3
                                    ? 'title3 notice'
                                    : temperature1Obj.level == 2
                                    ? 'title3 notice1'
                                    : 'title3'
                                  : 'title3'
                              }
                            >
                              {itemData.temperature1}
                            </div>
                          </div>
                        </div>
                      </div>
                    )}
                </>
              )}
            </>
          )}
        </div>
        {/* 报警 */}
        {targetAlarms?.length > 0 && (
          <Popconfirm
            title="生理报警"
            icon={<></>}
            showCancel={false}
            okType="default"
            okText="关闭"
            onConfirm={() => {}}
            description={() => {
              return (
                <div className="alarm-list-wrapper">
                  {targetAlarms.map((items: any, index: number) => {
                    return (
                      <div
                        className={
                          targetAlarms[index]?.level == 2
                            ? 'alarm-item-wrapper medium'
                            : targetAlarms[index]?.level == 3
                            ? 'alarm-item-wrapper high'
                            : 'alarm-item-wrapper'
                        }
                        key={index + '-alarm-item-wrapper'}
                      >
                        <p className="alarm-msg-content">{items.msg}</p>
                      </div>
                    );
                  })}
                </div>
              );
            }}
          >
            {targetAlarms[currentIndex] && (
              <div
                className={
                  targetAlarms[currentIndex]?.level == 2
                    ? 'alarm-show-wrapper medium'
                    : targetAlarms[currentIndex]?.level == 3
                    ? 'alarm-show-wrapper high'
                    : 'alarm-show-wrapper'
                }
              >
                <p
                  className="alarm-msg-content"
                  dangerouslySetInnerHTML={{
                    __html: targetAlarms[currentIndex].msg,
                  }}
                />
                <EllipsisOutlined className="alarm-msg-icon" />
              </div>
            )}
          </Popconfirm>
        )}
        {/* 确认弹层 */}
        <ModalConfirm
          ref={modalConfirmRef}
          successCallback={modalSuccessCallback}
        />
        <ScreenAreaPatientMsg
          ref={ScreenAreaPatientMsgRef}
          refreshList={refreshList}
          ecgModuleItem={itemData}
        />
        {/* 报警限判断 */}
        <AlarmLimit ref={AlarmLimitRef} refreshList={refreshList} />
      </div>
    );
  },
);

export default EcgModule;
